<template>
  <div class="common-layout">
    <el-container>
      <el-main style="height: 300px;">
        <div class="storage-area-management">
          <el-button @click="dialogVisible = true" type="primary">添加</el-button>
          <el-table :data="storageAreaList" style="width: 100%;">
            <el-table-column type="index" label="序号" />
            <el-table-column prop="materialName" label="物资名称" />
            <el-table-column prop="dict_Item" label="计量个数" width="150">
              <template #default="scope">
                {{ scope.row.dict_Item === 1 ? '支' : scope.row.dict_Item === 2 ? '个' : scope.row.dict_Item === 3 ? '斤' :
                  '组' }}
              </template>
            </el-table-column>
            <el-table-column label="创建时间">
              <template #default="scope">{{ scope.row.create_Time.substring(0, 10) }}</template>
            </el-table-column>
            <el-table-column label="操作" width="160px">
              <template #default="scope">
                <el-button type="success" size="small" link @click="handleOpenEditDialog(scope.row)">编辑</el-button>
                <el-button type="warning" size="small" link @click="handleOpenEditDialog(scope.row)">查看</el-button>
                <el-button type="danger" size="small" link @click="deleteStorageAreaAPI(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-main>
      <el-footer>
        <el-pagination style="margin-top: 10px;" v-model:current-page="paging.pageIndex"
          v-model:page-size="paging.pageSize" :page-sizes="[3, 5, 7]" :background="true"
          layout="total, sizes, prev, pager, next, jumper" :total="paging.totalCount" />
      </el-footer>
    </el-container>
  </div>

  <!-- 添加库区弹框 -->
  <el-dialog v-model="dialogVisible" title="添加库区" width="800" :inline="true" draggable>
    <el-form>
      <el-row>
        <el-col :span="12">
          <el-form-item label="物资名称">
            <el-input placeholder="请输入物资名称" v-model="form.materialName" style="width: 120px" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计量单位" style="width: 200px">
            <el-select placeholder="请选择" v-model="form.Dict_Item" clearable>
              <el-option label="支" :value="1" />
              <el-option label="个" :value="2" />
              <el-option label="斤" :value="3" />
              <el-option label="组" :value="4" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="物资分类" style="width: 200px">
            <el-select placeholder="请选择" v-model="form.Material_CategoryId" clearable>
              <el-option label="Apple " :value="1" />
              <el-option label="Sony" :value="2" />
              <el-option label="小熊饼干" :value="10" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="型号规格">
            <el-input placeholder="请输入型号规格" v-model="form.Spec" style="width: 120px" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最小预警库存">
            <el-input placeholder="请输入最小预警库存" v-model="form.Min_Stock" style="width: 120px" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最大预警库存">
            <el-input placeholder="请输入最大预警库存" v-model="form.Maxwarning" style="width: 120px" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="addStorageAreaAPI">确定</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 编辑库区弹框 -->
  <el-dialog v-model="editdialogVisible" title="编辑库区" width="800" :inline="true" draggable>
    <el-form>
      <el-row>
        <el-col :span="12">
          <el-form-item label="物资名称">
            <el-input placeholder="请输入物资名称" v-model="editform.materialName" style="width: 120px" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计量单位" style="width: 200px">
            <el-select placeholder="请选择" v-model="editform.Dict_Item" clearable>
              <el-option label="支" :value="1" />
              <el-option label="个" :value="2" />
              <el-option label="斤" :value="3" />
              <el-option label="组" :value="4" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="物资分类" style="width: 200px">
            <el-select placeholder="请选择" v-model="editform.Material_CategoryId" clearable>
              <el-option label="Apple " :value="1" />
              <el-option label="Sony" :value="2" />
              <el-option label="小熊饼干" :value="10" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="型号规格">
            <el-input placeholder="请输入型号规格" v-model="editform.Spec" style="width: 120px" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最小预警库存">
            <el-input placeholder="请输入最小预警库存" v-model="editform.Min_Stock" style="width: 120px" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最大预警库存">
            <el-input placeholder="请输入最大预警库存" v-model="editform.Maxwarning" style="width: 120px" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="editStorageAreaAPI">确定</el-button>
        <el-button @click="editdialogVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { materialsmanagementshow, suppliesadd, supplieslook, suppliesdel } from "@/api/Index";

// 查询条件
const form = reactive({
  MaterialId: 0,
  Material_CategoryId: '',
  materialName: "",
  Dict_Item: "",
  storage_areaStatus: "",
  Spec: "",
  Min_Stock: "",
  Maxwarning: "",
});

const editform = reactive({
  MaterialId: '',
  Material_CategoryId: '',
  materialName: "",
  Dict_Item: "",
  storage_areaStatus: "",
  Spec: "",
  Min_Stock: "",
  Maxwarning: "",
});

// 分页信息
const paging = reactive({
  pageIndex: 1,
  pageSize: 5,
  totalCount: 1,
  pageCount: 1,
});

const router = useRouter();
const dialogVisible = ref(false);
const editdialogVisible = ref(false);
const storageAreaList = ref<any>([]);

// 获取存储区域列表
const getStorageAreaListAPI = () => {
  const getStorage = ref({
    PageIndex: paging.pageIndex,
    PageSize: paging.pageSize,
  });
  materialsmanagementshow(getStorage.value).then(res => {
    storageAreaList.value = res.data.list;
    paging.totalCount = res.data.totalCount;
    paging.pageCount = res.data.totalPage;
  });
};

// 添加存储区域
const addStorageAreaAPI = () => {
  const adddata = ref({
    MaterialName: form.materialName,
    Dict_Item: form.Dict_Item,
    Material_CategoryId: form.Material_CategoryId,
    Spec: form.Spec,
    Min_Stock: form.Min_Stock,
    Maxwarning: form.Maxwarning,
  });
  suppliesadd(adddata.value).then(res => {
    if (res.isSuc) {
      ElMessage.success("添加成功");
      dialogVisible.value = false;
      getStorageAreaListAPI();
    } else {
      ElMessage.error(res.data.message);
    }
  });
};

// 编辑存储区域
const editStorageAreaAPI = () => {
  const updatedata = ref({
    MaterialId: editform.MaterialId,
    MaterialName: editform.materialName,
    Dict_Item: editform.Dict_Item,
    Material_CategoryId: editform.Material_CategoryId,
    Spec: editform.Spec,
    Min_Stock: editform.Min_Stock,
    Maxwarning: editform.Maxwarning,
  });
  supplieslook(updatedata.value).then(res => {
    if (res.isSuc) {
      ElMessage.success("编辑成功");
      editdialogVisible.value = false;
      getStorageAreaListAPI();
    } else {
      ElMessage.error(res.message);
    }
  });
};

// 删除存储区域
const deleteStorageAreaAPI = async (row: any) => {
  try {
    // 确认删除
    const confirmResult = await ElMessageBox.confirm('确定删除该分类吗？', '提示', {
      type: 'warning',
    });

    // 如果用户点击了取消，confirmResult 会是 'cancel'，直接返回
    if (confirmResult === 'cancel') {
      return;
    }

    // 提交删除请求
    const delstro = ref({
      materialId: row.materialId,
    });

    const res = await suppliesdel(delstro.value);
    if (res.isSuc) {
      ElMessage.success('删除成功');
      getStorageAreaListAPI(); // 刷新数据
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    // 捕获错误（例如用户点击取消或请求失败）
    ElMessage.error('取消删除或请求失败');
  }
};

// 打开编辑对话框
const handleOpenEditDialog = (row: any) => {
  editform.MaterialId = row.materialId;
  editform.materialName = row.materialName;
  editform.Dict_Item = row.dict_Item;
  editform.Material_CategoryId = row.material_CategoryId;
  editform.Spec = row.spec;
  editform.Min_Stock = row.min_Stock;
  editform.Maxwarning = row.maxwarning;
  editdialogVisible.value = true;
};

// 监听分页信息变化
watch(paging, () => {
  getStorageAreaListAPI();
});

// 组件挂载后获取数据
onMounted(() => {
  getStorageAreaListAPI();
});
</script>

<style scoped>
.storage-area-management {
  margin: 20px;
}
</style>